package com.itheima.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 用户信息操作
 * 权限控制
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    //根据用户名查询数据库用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);//查询用户基本信息，不包括用户角色
        if (user== null){
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role:roles){
            Integer roleId = role.getId();
            //根据角色id，查询用户权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            //让角色关联权限
            role.setPermissions(permissions);
        }
        //让用户关联角色
        user.setRoles(roles);
        return user;
    }

    //添加用户
    @Override
    public void add(User user, Integer[] roleIds) {
        // springsecurity 注册加密方法
        /*BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("1");*/
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode =  bCryptPasswordEncoder.encode(password);
        user.setPassword(encode);
        userDao.add(user);
        Integer userId = user.getId();
        this.setUserAndRole(userId,roleIds);
    }

    //分页管理
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        //        mybatis 分页助手
        PageHelper.startPage(currentPage,pageSize);
        Page<User> page = userDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    //回显用户基本信息
/*    @Override
    public User copyback(Integer id) {
        User user = userDao.copyback(id);
        return user;
    }*/

    @Override
    public User copyback(String username) {
        User user = userDao.findByUsername(username);
        return user;
    }

    //回显用户角色信息
    @Override
    public List<Integer> copybackids(Integer id) {
        List<Integer> roleIdList = userDao.copybackIds(id);
        return roleIdList;
    }

    //编辑用户
    @Override
    public void edit(User user, Integer[] roleIds) {
        //修改用户信息
//        userDao.edit(user);
//        Integer userId = user.getId();
        //将关系进行清除
//        userDao.deleteAssociation(userId);
        //重新设置关联关系
//        this.setUserAndRole(userId,roleIds);


        //清理当前检查组关联的检查项，操作中间关系表
        userDao.deleteAssociation(user.getId());

        //重新建立当前检查组和检查项的关系
/*        if (checkitemIds != null && checkitemIds.length >0){
            Arrays.stream(checkitemIds).forEach(checkitemId->{
                HashMap<String, Integer> map = new HashMap<>();
                map.put("checkgroup_id", checkGroup.getId());
                map.put("checkitem_id",checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            });
        }*/



        //new CheckGroup().setCode().se;
        // lombok 链式编程

        if (roleIds != null && roleIds.length >0) {
            for (Integer checkitemId : roleIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("user_id", user.getId());
                map.put("role_id", checkitemId);
                userDao.setUserAndRole(map);
            }
        }

        //修改检查组基本信息，操作检查组t_checkgroup_checkitem表
        userDao.edit(user);
    }

    //删除用户
    @Override
    public void del(Integer id) {
        //先删除关联关系  中间表的
        userDao.deleteAssociation(id);
        //删除用户
        userDao.del(id);
    }

    //查询用户
    @Override
    public List<User> findalluser() {
        List<User> userList = userDao.findalluser();
        return userList;
    }

    //抽取
    public  void  setUserAndRole(Integer userId,Integer[] roleIds){
        if (roleIds !=null && roleIds.length>0){
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("role_id",roleId);
                map.put("user_id",userId);
                userDao.setUserAndRole(map);
            }
        }
    }
}
